<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Model\Channel;
use App\Model\data\CurrentShopData;
use App\Model\Landmark;
use App\Model\LinkChannel;
use App\Model\LinkFile;
use App\Model\LinkIndustry;
use App\Model\Product;
use App\Model\ProductAudit;
use App\Model\ProductSpecKey;
use App\Model\ProductSpecValue;
use App\Model\Sku;
use App\Model\SkuAudit;
use App\Model\TransportMode;
use App\Service\SkuService;
use App\Service\SkuAuditService;
use App\Model\SkuPrice;
use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\ApplicationContext;
use App\Library\Common;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class ProductService extends BaseService
{
    const PRODUCT_FIELD = ['id', 'product_name', 'shop_id', 'fileinfo_id', 'is_illegal', 'is_show', 'sales_actual',
        'check_status', 'category_id', 'industry_id', 'delivery_id', 'type', 'center_id', 'check_status', 'specialty_id', 'landmark_id', 'is_origin_made',
        'created_at', 'updated_at', 'deleted_at', 'push_at', 'create_by', 'update_by',
        'delete_by', 'min_single_price', 'views_times', 'sales_actual'];

    /**
     * 审核
     * @Inject
     * @var ProductAuditRefuseService
     */
    private $ProductAuditRefuseService;

    /**
     * @Inject
     * @var SkuService
     */
    private $SkuService;
    /**
     * @Inject
     * @var SkuAuditService
     */
    private $SkuAuditService;
    /**
     * @Inject
     * @var ProductSpecKeyService
     */
    private $ProductSpecKeyService;

    /**
     * @Inject
     * @var ProductSpecValueService
     */
    private $ProductSpecValueService;

    /**
     * @Inject
     * @var LinkFileService
     */
    private $LinkFileService;


    /**
     * @Inject
     * @var LinkChannelService
     */
    private $LinkChannelService;

    /**
     * 查询单条  包括关联关系
     * @param int $id
     * @return object
     */
    public function info(int $id)
    {
        //审核下详情、
        return Product::query()
            ->where('id', $id)
            ->with(['create_info', 'update_info', 'delete_info'])
            ->with(['sku_list', 'main_pic', 'detail_pic', 'file_info', 'link_channel', 'industry_info', 'spec_key',
                'shop_info', 'landmark_info', 'specialty_info'
                , 'file_info'
                , 'shop_min_sku'
                , 'delivery_info'
                , 'transport_info'
                , 'cate_info'
                , 'reviews_list'
                , 'reason_info', 'refuse_info'])
            ->with(['audit_info', 'certify_info'])
            ->with('shop_min_sku')
            ->withCount('reviews')
            ->withCount(['sku_list as totla_inventory' => function ($query) {
                $query->select(DB::raw("sum(inventory)"));
            }])
            ->first(self::PRODUCT_FIELD);
    }

    /**
     *  * 查询列表
     * @param array $params
     * @param int $type
     * @return object
     */
    public function index(array $params, $type = 1)
    {
        $industry_ids = isset($params['industry_ids']) ? $params['industry_ids'] : [];
        $center_ids = isset($params['center_ids']) ? $params['center_ids'] : [];
        $channel_ids = isset($params['channel_ids']) ? $params['channel_ids'] : [];
        $key_word = isset($params['key_word']) ? $params['key_word'] : '';
        $auth_type = isset($params['auth_type']) ? $params['auth_type'] : [];
        $push_by = isset($params['push_by']) ? $params['push_by'] : 1;
        $is_show = isset($params['is_show']) ? $params['is_show'] : '';
        $check_status = isset($params['check_status']) ? $params['check_status'] : '';
        $status = isset($params['status']) ? $params['status'] : [];
        $good_type = isset($params['type']) ? $params['type'] : 1;

//        排序处理
        $order_by = isset($params['order_by']) ? intval($params['order_by']) : '1';
        $order_by_name = 'push_at';
        $order = 'ASC';
        switch ($order_by) {
            case 1:
                $order_by_name = 'views_times';
                $order = 'DESC';
                break;
            case 2:
                $order_by_name = 'sales_actual';
                $order = 'DESC';
                break;

        }
//        是否违规

        $Product = new Product();
        $where = [];
        $auth_ids = $ids = [];
        if ($type == 1) {
            $shop_info = CurrentShopData::getData();
            if ($shop_info) {
                $where['shop_id'] = $shop_info->id;
            }
        } else {
            $shop_id = isset($params['shop_id']) ? $params['shop_id'] : '';
            if ($shop_id) {
                $where['shop_id'] = $shop_id;
            }
        }
        $is_illegal = (isset($params['is_illegal']) && $params['is_illegal'] !== '') ? $params['is_illegal'] : '';
        if ($is_illegal !== '') {
            $where['is_illegal'] = $is_illegal;
        }
        if ($check_status !== '') {
            $where['check_status'] = $check_status;
        }
        if ($good_type !== '') {
            $where['type'] = $good_type;
        }

        if ($is_show !== '') {
            $where['is_show'] = $is_show;
        }
        if ($auth_type) {
//            认证类型筛选 恶心，自己是or  外部是and
            $origin_made_union = $Product
                ->when(in_array(1, $auth_type), function ($query) {
                    $query->where(['is_origin_made' => 1])->pluck('id');
                })
                ->pluck('id')->toArray();
            $landmark_union = $Product
                ->when(in_array(2, $auth_type), function ($query) {
                    $query->where('landmark_id', '!=', '0')->pluck('id');
                })
                ->pluck('id')->toArray();
            $specialty_union = $Product
                ->when(in_array(3, $auth_type), function ($query) {
                    $query->where('specialty_id', '!=', '0')->pluck('id');
                })
                ->pluck('id')
                ->toArray();
//            合并去重复
            $auth_ids = array_unique(array_merge($specialty_union, array_merge($origin_made_union, $landmark_union, $specialty_union)));
        }

        $link_product_ids = [];
        if ($channel_ids) {
            $link_product_ids = LinkChannel::query()->where('type', '1')->whereIn('channel_id', $channel_ids)->pluck('link_id');
            if ($link_product_ids) {
                $link_product_ids = $link_product_ids->toArray();
            } else {
                $link_product_ids = [];
            }
        }

        if ($key_word) {
            $ids = Sku::query()->where('sku_name', 'like', '%' . $key_word . '%')->pluck('product_id');
            if ($ids) {
                $ids = $ids->toArray();
            } else {
                $ids = [];
            }
        }
        return
            $Product
                ->where($where)
                ->where(function ($query) use ($key_word, $ids) {
                    if (!empty($key_word)) {
                        $query->whereIn('id', $ids)
                            ->orWhere('product_name', 'like', '%' . $key_word . '%');
                    }
                })
                ->when($auth_type, function ($query) use ($auth_ids) {
                    $query->whereIn('id', $auth_ids);
                })
                ->when($industry_ids, function ($query) use ($industry_ids) {
                    $query->whereIn('industry_id', $industry_ids);
                })
                ->when($center_ids, function ($query) use ($center_ids) {
                    $query->whereIn('center_id', $center_ids);
                })
                ->when($channel_ids, function ($query) use ($link_product_ids) {
                    $query->whereIn('id', $link_product_ids);
                })
                ->when($status != [], function ($query) use ($status) {
                    $query->whereIn('check_status', $status);
                })
                ->with(['create_info', 'update_info', 'delete_info'])
                ->with([
                    'sku_list', 'main_pic', 'detail_pic', 'link_channel', 'industry_info', 'spec_key',
                    'shop_info', 'landmark_info', 'specialty_info'
                    , 'file_info'
                    , 'reason_info'
                    , 'refuse_info'
                    , 'cate_info'
                ])
                ->with(['transport_info'])
                ->with('shop_min_sku')
                ->orderBy('push_at', $push_by == 1 ? 'DESC' : 'ASC')
                ->orderBy($order_by_name, $order)
                ->select(self::PRODUCT_FIELD)
                ->withCount(['sku_list as total_inventory' => function ($query) {
                    $query->select(DB::raw("sum(inventory)"));
                }]);
    }

    //   跳过认证的发布

    /**
     * @param array $params
     * @return bool
     */

    public function product_push($params)
    {
        return Product::query()->where('id', $params['id'])->update($params);
    }


    /**
     * Notes:获取最高最低价
     * @param int $product_id
     * @param int $type
     * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|void|null
     * Date: 2022/8/9
     * Time:15:17
     * Auth: zdl
     */
    public function product_best_price(int $product_id,$type=1)
    {
//        1最低价  2最高价
        $desc = 'DESC';
        if($type==2){
            $desc = 'ASC';
        }
       return SkuPrice::query()
            ->leftJoin('fly_sku as sku','fly_sku_price.sku_id','sku.id')
            ->where('sku.product_id',$product_id)
            ->orderBy('fly_sku_price.single_price',$desc)
           ->value('fly_sku_price.single_price');
    }



    //   撤销认证的发布

    /**
     * @param array $params
     * @return bool
     */
    public function cancel_push($params)
    {
        $product_id = $params['id'];
        $upArr = [];
        $upArr['check_status'] = 1;
//        查询通过的审核结果
        $old_info = (new ProductAuditService())->old_info($product_id);

//       上次审核通过的数据
        $channel = [];
        if ($old_info) {
            $old_info = $old_info->toArray();
            if ($old_info['link_channel_audit']) {
                $channel = array_column($old_info['link_channel_audit'], 'channel_id');
            }
            if ($old_info['landmark_id'] == '') {
                $upArr['landmark_id'] = 0;
            } else {
                $upArr['landmark_id'] = $old_info['landmark_id'];
            }
        } else {
            $upArr['landmark_id'] = 0;
        }
        //           清除没有审核的
        LinkChannel::query()->where('link_id', $product_id)
            ->where('type', 1)
            ->whereNotIn('channel_id', $channel)
            ->delete();
        Product::query()->where('id', $product_id)->update($upArr);
        ProductAudit::query()
            ->where([
                    'product_id' => $product_id,
                    'audit_type' => 1]
            )
            ->whereIn('audit_status', [0, -1])
            ->update(['audit_status' => -1]);

        $this->es_push($params['id'], 1);
        return true;
    }
    //   新增单条  包括关联关系

    /**
     * @param array $insertData
     * @return bool
     */

    public function insert(array $insertData)
    {

        $shop_info = CurrentShopData::getData();
        if ($shop_info) {
            $shop_info = $shop_info->toArray();
            $insertData['shop_id'] = $shop_info['id'];
        } else {
            $insertData['shop_id'] = 0;
        }
        $spec_key = $sku_list = $key_arr = $detail_pic = $main_pic = $channel = [];
        if (isset($insertData['spec_key'])) {
            $spec_key = $insertData['spec_key'];
            unset($insertData['spec_key']);
        }
        if (isset($insertData['sku'])) {
            $sku_list = $insertData['sku'];
            unset($insertData['sku']);
        }
        if (isset($insertData['channel'])) {
            $channel = $insertData['channel'];
            unset($insertData['channel']);
        }

        $transport_mode = [];
        if (isset($insertData['transport_mode'])) {
            $transport_mode = $insertData['transport_mode'];
            unset($insertData['transport_mode']);
        }


        if (isset($insertData['main_pic'])) {
            $main_pic = $insertData['main_pic'];
            unset($insertData['main_pic']);
        }
        if (isset($insertData['detail_pic'])) {
            $detail_pic = $insertData['detail_pic'];
            unset($insertData['detail_pic']);

        }

        $product_id = '';
        $product_id = $this->insertGetId(Common::filter_null($insertData));
        if (count($spec_key) > 0) {
            $key_arr = $this->ProductSpecKeyService->key_update_insert($spec_key, $product_id);
        }
        if (count($main_pic) > 0) {
            $this->LinkFileService->link_file_insert($main_pic, $product_id, 2);
        }
        if (count($detail_pic) > 0) {
            $this->LinkFileService->link_file_insert($detail_pic, $product_id, 3);
        }
        if (count($transport_mode) > 0) {
            $this->link_mode_insert($transport_mode, $product_id);
        }
        return $product_id;
    }

    public function link_mode_insert($transport_mode, $product_id)
    {
        $modes = [];
        foreach ($transport_mode as $value) {
            $modes[] = [
                'product_id' => $product_id,
                'type' => $value,
            ];
        }
        $TransportMode = new TransportMode();
        $res1 = $TransportMode->where('product_id', $product_id)->delete();
        if (count($transport_mode) > 0) {
            $TransportMode->insert($modes);
        }
        return true;

    }

    public function get_spec_key($product_id)
    {
        return ProductSpecKey::query()->where('product_id', $product_id)->select()->get();
    }


    //    商品违规整改

    /**
     * @param int $product_id
     * @param array $upData
     * @return bool
     **/
    public function rectification($product_id, $upData)
    {
        $old_data = $this->getModelInstance()->find($product_id);
        $upData = Common::filter_null($upData);
        if ($old_data['check_status'] == -1) {
//            恢复到审核中
            $upData['check_status'] = 0;
            $this->update_insert(['id' => $product_id], $upData);

            if ($old_data['is_illegal'] == 1) {
//                修改审核
                $audit_id = $this->insert_off_audit(intval($product_id), 2);
            } else {
//                修改认证
                $audit_id = $this->insert_off_audit(intval($product_id), 1);
            }
        } else {
            $this->update_insert(['id' => $product_id], $upData);
        }
        return true;
    }


    /**
     * 统计
     * @param int $shop_id
     * @param int $type
     * @return object
     */
    public function countSize($shop_id, $type = 1)
    {
        return Product::query()
            ->where('shop_id', $shop_id)
            ->where('type', $type)
            ->selectRaw("
                count(case when is_show !=3 then 1 end) as total_num,
                count(case when (is_show = 1 AND check_status=1 AND is_illegal=0) then 1 end) as show_num,
                count(case when (is_show = 0 AND check_status=1 AND is_illegal=0) then 1 end) as un_show_num,
                count(case when is_illegal=1 then 1 end) as illegal_num,
                count(case when is_illegal=0 AND check_status!=1 then 1 end) as audit_num",
            )
            ->first();
    }

    //    简单的商品详情

    /**
     * @param int $id
     * @return array
     **/
    public function single_info($id)
    {
        $info = Product::query()
            ->where('id', $id)
//            ->with(['create_info','update_info','update_info'])
//            ->with(['sku_list','main_pic','detail_pic','link_channel','industry_info','spec_key','shop_info','landmark_info','center_info','specialty_info'])
            ->with(['sku_list', 'main_pic', 'detail_pic', 'link_channel', 'spec_key'])
            ->first(self::PRODUCT_FIELD)->toArray();
        return $info;
    }

    // 商品违规整改  1认证  2违规
    public function insert_off_audit($product_id, $type = 1)
    {
        $ProductAudit = new ProductAudit();
        $product_info = $this->single_info($product_id);

        $product_info['product_id'] = $product_info['id'];
        unset($product_info['id']);

        $product_info['spec_key'] = $product_info['spec_key'] ? json_encode(array_column($product_info['spec_key'], 'spec_name')) : '[]';

        $product_info['audit_type'] = $type;
        $product_info['audit_status'] = 0;
        $product_info['audit_by'] = 0;
        $main_pic = $product_info['main_pic'];
        unset($product_info['main_pic']);

        $channel = $product_info['link_channel'];
        unset($product_info['link_channel']);
        $detail_pic = $product_info['detail_pic'];
        unset($product_info['detail_pic']);
        $sku_list = $product_info['sku_list'];
        unset($product_info['sku_list']);
        $off_data = [];
        if ($type == 2) {
//            通过product_获取最新的
            $off_data = $this->ProductAuditRefuseService->first_refuse($product_id, 2);

        }
        if ($type == 1) {
//            通过product_获取最新的
            $off_data = $this->ProductAuditRefuseService->first_refuse($product_id, 1);

        }

        $audit_id = $ProductAudit->insertGetId($product_info);

        if ($off_data != []) {
            $this->ProductAuditRefuseService->refuse_insert($audit_id, $off_data['reason_json'], $off_data['tips'], 2);
        }

        if ($sku_list) {
            $this->SkuAuditService->sku_audit_insert_with_search($sku_list, $product_id, $audit_id);
        }
        if (count($main_pic) > 0) {
            $this->LinkFileService->link_file_insert(array_column($main_pic, 'fileinfo_id'), $audit_id, 4);
        }
        if (count($detail_pic) > 0) {
            $this->LinkFileService->link_file_insert(array_column($detail_pic, 'fileinfo_id'), $audit_id, 5);
        }
//        频道


        if (count($channel) > 0) {
            $this->LinkChannelService->insert_or_update($channel, $audit_id, 2);
        }
        return $audit_id;
    }

//    审核记录
    public function insert_audit(array $upData, $product_id, $main_pic, $detail_pic, $channel, $spec_key)
    {

        $shop_info = CurrentShopData::getData();
        $upData['shop_id'] = $shop_info->id;
        $ProductAudit = new ProductAudit();

        $upData['product_id'] = $upData['id'];
        $product_info = [];
        $product_info = $this->info($product_id);
        if ($product_info) {
            $product_info = $product_info->toArray();
        }
        unset($upData['id']);
        $upData['spec_key'] = json_encode($spec_key);
        $upData['audit_type'] = 1;
        $upData['product_name'] = $product_info['product_name'];
        $upData['delivery_id'] = $product_info['delivery_id'];
        $upData['created_at'] = $product_info['created_at'];
        $upData['create_by'] = $product_info['create_by'];
        $upData['min_single_price'] = $product_info['min_single_price'];
        if ($product_info['spec_key'] != '') {
            $upData['spec_key'] = array_column($product_info['spec_key'], 'spec_name');
        } else {
            $upData['spec_key'];
        }
        $upData['spec_key'] = json_encode($upData['spec_key']);
        $audit_id = $ProductAudit->insertGetId($upData);
        $sku_list = Sku::query()->where('product_id', $product_id)->with('spec_value', 'step_price')->select()->get();
        if ($sku_list) {
            $sku_list = $sku_list->toArray();
            $this->SkuAuditService->sku_audit_insert($sku_list, $product_id, $audit_id);
        }

        if (count($main_pic) > 0) {
            $this->LinkFileService->link_file_insert($main_pic, $audit_id, 4);
        }
        if (count($detail_pic) > 0) {
            $this->LinkFileService->link_file_insert($detail_pic, $audit_id, 5);
        }
//        频道
        if (count($channel) > 0) {
            $this->LinkChannelService->insert_or_update($channel, $audit_id, 2);
        }
        return $audit_id;
    }

    public function insertGetId(array $insertData)
    {
        return Product::query()->insertGetId(Common::filter_null($insertData));
    }

    public function channel_insert(array $channel_insert, $product_id, $type = 1): bool
    {
        $arr = [];
        $LinkChannel = new LinkChannel();
        foreach ($channel_insert as $key => $value) {
            $arr[] = [
                'link_id' => $product_id,
                'channel_id' => $value,
                'type' => $type,
            ];
        }
        $LinkChannel->insert($arr);
        return true;
    }

    //    关联数据插入
    public function spec_value_insert(array $skuData, $product_id)
    {
        $arr = [];
        foreach ($skuData as $key => $value) {
            $value['product_id'] = $product_id;
            $arr[] = $value;
        }
        ProductSpecValue::query()->insert($arr);
        return true;
    }

//    更新product
    public function product_update(array $upData)
    {
        $transport_mode = $spec_key = $sku_list = $key_arr = $detail_pic = $main_pic = $channel = [];
        $product_id = $upData['id'];

        if (isset($upData['transport_mode'])) {
            $transport_mode = $upData['transport_mode'];
            unset($upData['transport_mode']);
            if (count($transport_mode) > 0) {
                $this->link_mode_insert($transport_mode, $product_id);
            }
        }
        if (isset($upData['spec_key'])) {
            $spec_key = $upData['spec_key'];
            unset($upData['spec_key']);
//            $this->productService->edit_spec($params['spec_key'],intval($params['product_id']));
            $this->edit_spec($spec_key, intval($upData['id']));
        }
        if (isset($upData['main_pic'])) {
            $main_pic = $upData['main_pic'];
            unset($upData['main_pic']);
        }
        $this->LinkFileService->link_file_insert($main_pic, $product_id, 2);
        if (isset($upData['detail_pic'])) {
            $detail_pic = $upData['detail_pic'];
            unset($upData['detail_pic']);
            $this->LinkFileService->link_file_insert($detail_pic, $product_id, 3);
        }
        if (count($transport_mode) > 0) {
            $this->link_mode_insert($transport_mode, $product_id);
        }
        //判断是修改还是整改
        return $this->rectification($product_id, $upData);
    }

    //    更新product审核
    public function product_update_link_audit(array $upData)
    {
        $spec_key = $sku_list = $key_arr = $detail_pic = $main_pic = $channel = [];
        $product_id = $upData['id'];
        $is_audit = $this->is_audit($upData);
        $channel = [];
        if (isset($upData['channel'])) {
            $channel = $upData['channel'];
            unset($upData['channel']);
            $this->LinkChannelService->insert_or_update($channel, $product_id, 1);
        }

        if ($is_audit == true) {
//           需要变更为未审核
            $audit_arr = $upData;
            $upData['check_status'] = 0;
            $this->insert_audit($upData, $product_id, $main_pic, $detail_pic, $channel, $spec_key);
        }
        $upData['push_at'] = date('Y-m-d H:i:s');
        $this->es_push($product_id, 1);
        return $this->update_insert(['id' => $product_id], $upData);
    }

    //检测审核start
    public function is_audit(array $upData)
    {
        $is_audit = false;
        if (isset($upData['channel']) && $upData['channel'] != []) {
//       或者地方特产不为空 是否有改变，有改变需要审核，其余不用处理
            $channel_old = $this->LinkChannelService->getDataByWhereForSelect(['link_id' => $upData['id'], 'type' => 1], 1);
            $channel_ids = array_column($channel_old, 'channel_id');
            if ($upData['channel'] != $channel_ids) {
                $is_audit = true;
            }

        }
        if (isset($upData['landmark_id']) && $upData['landmark_id'] != '') {
//            频道 是否有改变，有改变需要审核，其余不用处理
            $product_old = $this->getDataByWhereForSelect(['id' => $upData['id']]);
            if ($upData['landmark_id'] != $product_old['landmark_id']) {
                $is_audit = true;
            }
        }
        return $is_audit;
    }


    /**
     * get_best_price
     * @param int $product_id
     * @param int $order_by
     * @return string
     */
    public function get_best_price($product_id, $order_by = 1)
    {
        $price = SkuPrice::query()
            ->leftJoin('fly_sku as sku', 'sku.sku_id', '=', 'fly_sku_price.sku_id')
            ->where('sku.product_id', $product_id)
            ->orderBy('fly_sku_price.single_price', $order_by == 1 ? 'ASC' : 'DESC')
            ->first(['fly_sku_price.single_price']);
        if ($price) {
            return $price->single_price;
        } else {
            return '';
        }
    }

    /**
     * 根据商品ID返回有效商品
     * @param array $id
     * @return array
     */
    public function getProductById(array $id): array
    {
        if (empty($id)) return [];
        $return = [];
        foreach ($id as $p_id) {
            $p = $this->getModelInstance()->findFromCache($p_id);
            if (!empty($p) || !empty($p->toArray())) {
                $p = $this->getModelInstance()->with(['create_info', 'update_info', 'delete_info', 'sku_list', 'main_pic', 'shop_min_sku',
                    'detail_pic', 'link_channel', 'industry_info', 'spec_key', 'shop_info', 'landmark_info', 'specialty_info', 'refuse_info'])
                    ->find($p_id);
            } else {
                $p->loadCache(['create_info', 'update_info', 'delete_info', 'sku_list', 'main_pic', 'shop_min_sku',
                    'detail_pic', 'link_channel', 'industry_info', 'spec_key', 'shop_info', 'landmark_info', 'specialty_info', 'refuse_info']);
            }
            if (!empty($p) || !empty($p->toArray())) {
                if (($p->is_illegal == 0 && $p->check_status == 1 && $p->is_show == 1)) {
                    $return[] = $p->toArray();
                }
            }
        }
        return $return;
    }


    //    关联数据插入
    public function sku_audit_insert_with_search(array $sku_list, int $product_id, int $audit_id)
    {
        $audit_arr = [];
        foreach ($sku_list as $key => $value) {
            unset($value['file_info']);
            $value['spec_value'] = json_encode($value['spec_value']);
            $value['step_price'] = json_encode($value['step_price']);
            $value['audit_id'] = $audit_id;
            $audit_arr[] = $value;
        }
        if ($audit_arr) {
            var_dump(SkuAudit::query()->insert($audit_arr));
        }
        return true;
    }


//    单独修改参数名
    public function edit_spec(array $spec_key, int $product_id)
    {
        $arr = [];
        $ProductSpecKey = new ProductSpecKey();
//        不在数组内的删除
        $ids = array_filter(array_column($spec_key, 'id'));
        $re1 = $ProductSpecKey
            ->where('product_id', $product_id)
            ->whereNotIn('id', $ids)
            ->delete();
        foreach ($spec_key as $key => $value) {
//            有id的修改，没有的新增
            if ($value['id'] != '') {
                $ProductSpecKey
                    ->where('product_id', $product_id)
                    ->where('id', $value['id'])
                    ->update(['spec_name' => $value['spec_name']]);
            } else {
                $arr[] = [
                    'spec_name' => $value['spec_name'],
                    'product_id' => $product_id,
                ];
            }
        }
        if (count($arr) > 0) {
            $re2 = $ProductSpecKey->insert($arr);
        }
        return true;
    }

    public function up($param, $func = 0, $type = 0)
    {
        try {
            $id = $param['id'];
            $shop_id = $param['shop_id'];
            if ($id == 0) {
//                有时候参数是product_id
                $id = $param['product_id'];
            }
            if ($func == 'shop_product_add' && $shop_id != 0) {
                $res = make(EsService::class)->shop_product_add(intval($shop_id), intval($type));
                $res2 = $this->es_push(intval($shop_id), 4);
                var_dump($res);
                var_dump('shop_product_add-' . $res);
            }
            if ($func == 'shop_product_clear' && $shop_id != 0) {
                $res = make(EsService::class)->shop_product_clear(intval($shop_id), intval($type));
                $res2 = $this->es_push(intval($shop_id), 4);
                var_dump($res);
                var_dump('shop_product_clear-' . $res);
            }
            if ($id != 0 && $type != 0) {
//                单条的
                if ($func == 'add') {
                    $res = $this->es_push(intval($id), intval($type));
                    var_dump($res);
                    var_dump('add-' . $res);
                }
                if ($func == 'del') {
                    $res = make(EsService::class)->deleteDoc(intval($id), intval($type));
                    var_dump($res);
                    var_dump('del-' . $res);
                }
            }
        } catch (\Throwable $e) {
            var_dump($e->getMessage());
        }
    }
}